package cn.jekun.web.shop.service;

import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.Mobile;
import cn.jekun.component.base.validator.annotation.NotBlank;
import cn.jekun.component.base.validator.annotation.Num;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.RsAgent;
import cn.jekun.component.core.bean.gen.RsSms;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.CoreAuthService;
import cn.jekun.component.core.service.SMSService;
import cn.jekun.component.core.service.gen.RsSmsService;
import cn.jekun.component.core.service.gen.RsUserService;
import cn.jekun.web.agent.bean.Agent;
import cn.jekun.web.shop.bean.UserLogin;
import cn.jekun.web.shop.bean.UserShop;
import cn.jekun.web.shop.bean.UserShops;

/**
 * 登录Service
 * @author yuan
 *
 */
@Service(LoginService.BEAN_NAME)
public class LoginService extends ShopBaseService{
	public static final String BEAN_NAME="cn.jekun.web.shop.service.LoginService";
	
	@Resource(name=RsUserService.BEAN_NAME)
	RsUserService userService;
	
	@Resource(name=CoreAuthService.BEAN_NAME)
	CoreAuthService coreAuthService;
	
	@Resource(name = RsSmsService.BEAN_NAME)
	RsSmsService rsSmsService;
	
	@Resource(name=SMSService.BEAN_NAME)
	protected SMSService smsService;
	
	@Override
	public String getNamespace() {
		// TODO Auto-generated method stub
		return "ACTION_RS_USER_LOGIN";
	}
	
	/**
	 * 查询用户名下的商家列表(分店)
	 * @param userName
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public List<UserShops> getUserShops(Map map){
		return this.list(map);
	}

	//检查用户是否存在
	public RsUser one(@RsUser.AnnoUserName String userName){
		Map formMap=new HashMap<String, String>();
		formMap.put(RsUser.COL_USER_NAME, userName);
		SqlUtis.prepareSql(formMap
				, SqlUtis.getSQL(formMap,"a."+RsUser.COL_USER_NAME,Types.VARCHAR,SqlUtis.EQ)
				);
		
		return this.userService.one(formMap);
	}
	
	public RsUser one(@RsUser.AnnoUserName String userName,String id){
		Map formMap=new HashMap<String, String>();
		formMap.put(RsUser.COL_USER_NAME, userName);
		SqlUtis.prepareSql(formMap
				, SqlUtis.getSQL(formMap,"a."+RsUser.COL_USER_NAME,Types.VARCHAR,SqlUtis.EQ)
				);
		
		return this.userService.one(formMap);
	}
	
    /**
     *  检验是否登录
     * @param statementName
     * @param agentName
     * @param userId
     * @return
     */
	public UserLogin one(@NotBlank(message="statementName不能为空")String statementName,@RsAgent.AnnoAgentName String agentName,@RsUser.AnnoUserId String userId){
		Map formMap=new HashMap<String, String>();
		formMap.put("userName", agentName);
		formMap.put("userId", userId);
		return this.one(statementName,formMap);
	}
	
	
	/**
	 * 获取代理商列表
	 * @param statementName
	 * @param agentName
	 * @param userId
	 * @return
	 */
	public List<Agent> getAgentList(@NotBlank(message="statementName不能为空")String statementName,@RsAgent.AnnoAgentName String agentName,@RsUser.AnnoUserId String userId){
		Map formMap=new HashMap<String, String>();
		formMap.put("userName", agentName);
		formMap.put("userId", userId);
		return userService.list(statementName, formMap);
	}
	
	
	/**
	 * 是否为管理员
	 * @param userId
	 * @return
	 */
	public boolean isAdmin(@RsUser.AnnoUserId String userId){
		return coreAuthService.isAdmin(userId);
	}
	
	
	/**
	 * 验证手机和用户名是否绑定
	 * @param userName
	 * @param mobile
	 * @return
	 */
	public String getUserIdByMobile(@RsUser.AnnoUserName String userName,@RsUser.AnnoMobile String mobile){
		Map map=new HashMap();
		map.put("userName", userName);
		map.put("mobile", mobile);
		UserShop user=this.one(getStatementName("queryUserByMobile"), map);
		return user.getUserId();
	}
	
	
	/**
	 * 找回登录密码，发送手机验证码
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
	public JSONObject sendValidateCode(@Mobile(message="手机号码格式不正确")String mobile){

		JSONObject jsonObject = new JSONObject();
			SMSService.checkTime(mobile);//检查发送间隔
			//一天最多5条
			if(!this.smsService.checkOverTimes(mobile, 	Constants.RS_SMS_TYPE.RE_LOGIN_PWD, "24", 5)){
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"一天最多5条,请稍后再操作");
			}
			//发送手机验证码
			try {
				// 生成随机类
				Random random = new Random();
				// 取随机产生的认证码(6位数字)
				String sRand = "";
				for (int i = 0; i < 6; i++) {
					String rand = String.valueOf(random.nextInt(10));
					sRand += rand;
				}
				String content = "您正在找回登录密码，验证码"+sRand+"，请在页面填写，如非本人操作，请忽略。" ;
//				// 将认证码存入数据库
//				Map insertMap = new HashMap();
//				RsSms rsSms = new RsSms();
//				rsSms.setContent(content);
//				rsSms.setMemo(sRand);
//				rsSms.setMobile(mobile);
//				rsSms.setSmsTypeId(Constants.RS_SMS_TYPE.RE_LOGIN_PWD);// 找回商家登录密码验证码
//				insertMap.put("rsSms", rsSms);
//				rsSmsService.insert(insertMap);
				// 发送短信 
				String error = this.smsService.sendSMS(mobile, content, Constants.RS_SMS_TYPE.RE_LOGIN_PWD, sRand);
				if (error != null) {
					jsonObject.put(ErrorMsg.KEY_MESSAGE, error);
					return this.executeRerutnFail(jsonObject);
				}
				return this.executeRerutn(jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
				return this.executeRerutnFail(jsonObject);
			}
	}
	
	
	/**
	 * 验证短信验证码是否正确
	 * @param mobile
	 * @param validatecode
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject checkValidateCode(@Mobile(message="手机号码格式不正确")String mobile,@Num(length=6,message="短信验证码格式不正确")String validateCode){

		if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"手机号码不能为空");
		}
		if (StringUtils.isBlank(validateCode)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"短信验证码不为空");
		}
		JSONObject jsonObject = new JSONObject();
		// 短信验证码验证（查找最新的短信信息验证码）
		String tempCode = null;// 手机验证码
		Map tempSmsMap = new HashMap();
		tempSmsMap.put(RsSms.COL_MOBILE, mobile);
		tempSmsMap.put(RsSms.COL_SMS_TYPE_ID, Constants.RS_SMS_TYPE.RE_LOGIN_PWD);
		SqlUtis.prepareSql(tempSmsMap, "", 
				SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ),
				SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_SMS_TYPE_ID, Types.VARCHAR, SqlUtis.EQ), SqlUtis
				.orderBy(" a.create_time desc nulls last"));
		Page smsPage = new Page();
		smsPage.setPageSize(1);
		List<RsSms> smsList = this.rsSmsService.list(tempSmsMap, smsPage);
		if (smsList != null && smsList.size() == 1) {
			RsSms rsSms = smsList.get(0);
			tempCode = rsSms.getMemo();
		}
		if (!validateCode.equals(tempCode)) {
			throw new BusinessException("-3210",
					"验证码错误");
		}
		return executeRerutn(jsonObject);
	}
	
}
